//
//  ViewController.m
//  XQBluetooth
//
//  Created by 包月兴 on 16/6/11.
//  Copyright © 2016年 包月兴. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "XQBluetoothSDK.h"
#import "XQDeviceViewController.h"
#import "NSTimer+XQBlcokSupport.h"
#import "XQFirmwareModel.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,copy) UIBarButtonItem *rightButton;
@property (nonatomic,copy) UITableView *tableView;
@property (nonatomic,copy) NSMutableArray *dataArr;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    if (XQFirmwareModelInstance.uuid && ![XQFirmwareModelInstance.uuid isEqualToString:@""]) {
        //已经绑定设备
        XQDeviceViewController *vc = [[XQDeviceViewController alloc] init];
        vc.peripheral = nil;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else
    {
        //未绑定设备
        _dataArr = [NSMutableArray array];
        self.title = @"搜索设备";
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
        [self.view addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _rightButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBle)];
        self.navigationItem.rightBarButtonItem = _rightButton;
    
    }
}


-(void)searchBle
{
    if (_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    self.navigationItem.rightBarButtonItem = nil;
    __weak __typeof(&*self)weakSelf = self;
    
    [XQBleSDKInstance searchPeripheralWithDuration:5 peripheralDictionary:^(NSDictionary *peripheral) {
        [weakSelf p_addPeripheral:peripheral];
        [weakSelf.tableView reloadData];
    } peripheralArray:^(NSArray *peripherals) {
        weakSelf.navigationItem.rightBarButtonItem = weakSelf.rightButton;
    } failure:^(XQBluetoothError *error) {
        weakSelf.navigationItem.rightBarButtonItem = weakSelf.rightButton;
        XQBLELog(@"搜索失败:%@",[error description]);
    }];
}


#pragma mark ---UITableViewDataSource---


#pragma mark ---
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   // XQBLELog(@"_dataArr = %ld",_dataArr.count);
    return _dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    NSDictionary *dic = _dataArr[indexPath.row];
    CBPeripheral *per = dic[@"peripheral"];
    cell.textLabel.text = per.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d",abs([dic[@"RSSI"] intValue])];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [XQBleSDKInstance stopScan];
    NSDictionary *dic = _dataArr[indexPath.row];
    CBPeripheral *per = dic[@"peripheral"];
    XQDeviceViewController *vc = [[XQDeviceViewController alloc] init];
    vc.peripheral = per;
    [self.navigationController pushViewController:vc animated:YES];
}



#pragma mark ---private Method---

-(void)p_addPeripheral:(NSDictionary *)peripheralDic
{
    
    CBPeripheral *p = peripheralDic[@"peripheral"];
    NSInteger temp = -1;
        if (_dataArr.count > 0) {
            NSInteger count = _dataArr.count;
            for (NSInteger i= 0;i< count; i++) {
                CBPeripheral *per = _dataArr[i][@"peripheral"];
                if (per.identifier == NULL || p.identifier == NULL) {
                    continue;
                }
                if ([self p_UUIDSAreEqual:p.identifier UUID2:per.identifier]) {
                    temp = i;
                }
        }
            if (temp > -1) {
                [_dataArr removeObjectAtIndex:temp];
            }
            
    }
    [_dataArr addObject:peripheralDic];
}

#pragma mark ---外设对象比较
- (BOOL) p_UUIDSAreEqual:(NSUUID *)UUID1 UUID2:(NSUUID *)UUID2
{
    if ([UUID1.UUIDString isEqualToString:UUID2.UUIDString])
        return TRUE;
    else
        return FALSE;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
